import { getToken, setToken, removeToken,setUserNum } from "@/utils/auth";
import { login, getInfo,getUserList,register} from '@/api/user.js'

const state = {
   token: getToken(),
  userId: '',
  avatar: '',
  username: '',
  number: '',
  phone: '',
  email: '',
  roles: []
};

const mutations = {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, data) => {
      state.userId = data.id;
      state.avatar = data.avatar;
      state.username = data.username;
      state.number = data.number;
      state.phone = data.phone;
      state.email = data.email;
    },
  
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
};

const actions = {
  login({ commit }, userInfo) {
      const { number, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ number: number.trim(), password: password })
          .then(response => {
            const { data } = response
            commit('SET_TOKEN', data.token)
            setToken(data.token)
            setUserNum(data.number)
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
  
    // get user info
    getInfo({ commit }, userNumber) {
      return new Promise((resolve, reject) => {
        let par = { number: userNumber }
        getInfo(par).then(response => {
		console.log("===========",response)
          const userData = response.data
          commit('SET_USER', userData);
          let roles = []
          roles.push(userData.role)
          commit('SET_ROLES', roles)
          resolve(userData);
        }).catch(error => {
          reject(error);
        })
      })
  
    },
  
    // user logout
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        // logout(state.token).then(() => {
        removeToken() // must remove  token  first
        removeUserNumber()
        resolve()
      })
    },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
};
